import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from "@angular/core";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";
import {SharedService} from "../shared-service";
import {Router} from "@angular/router";
import {LocalStorageService} from "../local-storage-service";

declare var $: any;

@Component({
  template: `
    <div class="cllb comp" [style.width]="compw" [style.height]="comph" [style.top]="topv"
         [style.left]="leftv">
      <div class="content">
        <div class="title">
          <div class="title_text">{{comptitle}}</div>
        </div>
        <div class="body">
          <div class="input_form">
            <input type="text" placeholder="设备名称" name="sbmc" [(ngModel)]="s_obj.sbmc" (keydown)="quickSeach($event)"/>
            <span class="search-icon" (click)="getdata()"><i class="fa fa-search"></i></span>
          </div>
          <div class="mt-checkbox-inline">
            <label class="mt-radio">
              <input type="radio" name="sfzx" value="" checked (click)="getdata()"/> 全部
              <span></span>
            </label>&nbsp;&nbsp;&nbsp;&nbsp;
            <label class="mt-radio">
              <input type="radio" name="sfzx" value="0" (click)="getdata()"/> 在线
              <span></span>
            </label>&nbsp;&nbsp;&nbsp;&nbsp;
            <label class="mt-radio">
              <input type="radio" name="sfzx" value="1" (click)="getdata()"/> 离线
              <span></span>
            </label>
          </div>
          <div class="fztitle">
            <!--<div class="icon_ksgljg"><span class="glyphicon glyphicon-home"></span></div>-->
            <span>{{title}}</span>
          </div>
          <div class="fzroom chromescrollkf iecrollkf">
            <div class="fzitem" *ngFor="let fzitem of fzList">
              <div class="icon_expand" (click)="toggleFzexpand(fzitem)">
                <span *ngIf="fzitem.fzexpand">
                  <!--<i class="fa fa-caret-down"></i>-->
                   <i class="fa fa-minus-square-o"></i>
                </span>
                <span *ngIf="!fzitem.fzexpand">
                  <!--<i class="fa fa-caret-right"></i>-->
                <i class="fa fa-plus-square-o"></i>
                </span>
              </div>
              <div class="icon_checkbox">
                <label class="mt-checkbox">
                  <input type="checkbox" name="fzcheck" [checked]="fzitem.checked" (click)="checkedToggle(1,fzitem)"/>
                  <span></span>
                </label>
              </div>
              <div class="icon_ksgljg"><span class="glyphicon glyphicon-home"></span></div>
              <span [style.color]="fzitem.fzexpand?'#0FBEF0':'#000'">{{fzitem.fzmc}}</span>
              <div class="zdList" *ngIf="fzitem.fzexpand&&fzitem.zdList.length">
                <div class="zditem" *ngFor="let zdobj of fzitem.zdList" [class.zditem_active]="zdobj.active">
                  <ng-container *ngIf="zdobj.zxzt=='0'">
                    <!--在线-->
                    <div class="top" [ngClass]="{'top_run':zdobj.sd>0,'top_stop':zdobj.sd==0 }">
                      <div class="top_checkbox fl">
                        <label class="mt-checkbox">
                          <input type="checkbox" name="zd" [checked]="zdobj.checked" (click)="checkedToggle(2,zdobj)"/>
                          <span></span>
                        </label>
                      </div>
                      <div class="top_conent fl" (click)="checkedToggle(3,zdobj)">
                        <div class="topcontent_zdicon fl"
                             [ngClass]="{'topcontent_zdicon_run':zdobj.sd>0,'topcontent_zdicon_stop':zdobj.sd==0}"></div>
                        <div class="topcontent_txt1 fl">
                          <div class="clmc" [ngClass]="{'text_run':zdobj.sd>0,'text_stop':zdobj.sd==0}">{{zdobj.zdmc}}
                          </div>
                          <div class="dl">
                            <ng-container *ngIf="zdobj.dl==0">
                              <span style="color: #1FD330"><i class="fa fa-battery-empty"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl>0 && zdobj.dl<=25">
                              <span style="color: #1FD330">  <i class="fa fa-battery-quarter"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl>25 && zdobj.dl<=50">
                              <span style="color: #1FD330"> <i class="fa fa-battery-half"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl>50 && zdobj.dl<=75">
                              <span style="color: #1FD330"> <i class="fa fa-battery-three-quarters"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl>75 && zdobj.dl<100">
                              <span style="color: #1FD330"><i class="fa fa-battery-empty-4"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl==100">
                              <span style="color: #1FD330"> <i class="fa fa-battery-full"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                          </div>
                        </div>
                        <div class="topcontent_txt2 fl">
                          <div class="speed" [ngClass]="{'text_run':zdobj.sd>0,'text_stop':zdobj.sd==0}">
                            <span *ngIf="zdobj.sd>0">{{zdobj.sd}}km/h</span>
                            <span *ngIf="zdobj.sd==0">静止</span>
                          </div>
                          <div class="zxtz text_zx">{{zdobj.zxztmc}}</div>
                        </div>
                      </div>
                    </div>
                    <div class="footer" [ngClass]="{'footer_run':zdobj.sd>0,'footer_stop':zdobj.sd==0 }">
                      <div class="footer_btns" style="border-right: 1px solid #ffffff;" (click)="gotoPage(1)">轨迹回放</div>
                      <div class="footer_btns" style="border-right: 1px solid #ffffff;" (click)="gotoPage(2)">实时跟踪</div>
                      <div class="footer_btns">更多</div>
                    </div>
                  </ng-container>
                  <ng-container *ngIf="zdobj.zxzt=='1'">
                    <!--离线-->
                    <div class="top top_lx">
                      <div class="top_checkbox fl">
                        <label class="mt-checkbox">
                          <input type="checkbox" name="zd" [checked]="zdobj.checked" (click)="checkedToggle(2,zdobj)"/>
                          <span></span>
                        </label>
                      </div>
                      <div class="top_conent fl" (click)="checkedToggle(3,zdobj)">
                        <div class="topcontent_zdicon topcontent_zdicon_lx fl"></div>
                        <div class="topcontent_txt1 fl">
                          <div class="clmc text_lx">{{zdobj.zdmc}}</div>
                          <div class="dl">
                            <ng-container *ngIf="zdobj.dl==0">
                              <span style="color: #000"><i class="fa fa-battery-empty"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl>0 && zdobj.dl<=25">
                              <span style="color: #000">  <i class="fa fa-battery-quarter"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl>25 && zdobj.dl<=50">
                              <span style="color: #000"> <i class="fa fa-battery-half"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl>50 && zdobj.dl<=75">
                              <span style="color: #000"> <i class="fa fa-battery-three-quarters"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl>75 && zdobj.dl<100">
                              <span style="color: #000"><i class="fa fa-battery-empty-4"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                            <ng-container *ngIf="zdobj.dl==100">
                              <span style="color: #000"> <i class="fa fa-battery-full"></i></span>
                              <span class="dl_txt">{{zdobj.dl}}%</span>
                            </ng-container>
                          </div>
                        </div>
                        <div class="topcontent_txt2 fl">
                          <div class="speed text_lx">
                            <span *ngIf="zdobj.sd>0">{{zdobj.sd}}km/h</span>
                            <span *ngIf="zdobj.sd==0">静止</span>
                          </div>
                          <div class="zxtz text_lx">{{zdobj.zxztmc}}</div>
                        </div>
                      </div>
                    </div>
                    <div class="footer footer_lx">
                      <div class="footer_btns" style="border-right: 1px solid #ffffff;">轨迹回放</div>
                      <div class="footer_btns" style="border-right: 1px solid #ffffff;">实时跟踪</div>
                      <div class="footer_btns">更多</div>
                    </div>
                  </ng-container>
                </div>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [
    ".cllb{position:absolute;background-color:#fff;border:5px solid #ccc;}",
    ".content{width: calc(100%);height: calc(100%);}",
    ".content>.title{position: relative;width: 100%;height: auto;padding: 10px; border-bottom: 1px solid #ccc; color: rgb(138 143 151);}",
    ".title>.title_text{height: 15px;line-height: 15px;font-size: 15px;  width: auto;border-left: 5px solid #1477F3;padding-left: 10px}",
    ".content>.body{position: relative;width: 100%;height: calc(100% - 24px);padding: 10px 10px}",
    ".input_form{width: 100%;height: 35px;border: 1px solid #D7D7D7;}",
    ".input_form>input{border: none;height: 32px;line-height: 32px; width: calc(100% - 40px);padding: 0px 10px}",
    ".input_form>.search-icon{display: inline-block; width: 40px;text-align: center;font-size: 20px;cursor: pointer;color: #0051C4}",
    //list
    ".fztitle{}",
    ".fzroom{width: calc(100% - 17px);height: 490px;padding-left: 20px; overflow-y: auto}",
    ".fzroom>.fzitem{width: 100%;padding: 10px 0px}",
    // one fzitem
    ".icon_expand{float: left;padding-right: 10px;cursor: pointer;}", /*展开 折叠符号*/
    ".icon_checkbox{float:left;}", /*分组的复选框*/
    ".icon_ksgljg{display: inline-block;padding-right: 5px;color: #0FBEF0}", /*分组图标*/
    // onefz 下终端
    ".zdList{width: 100%;height: auto;padding-left: 50px}",
    //one  zditem
    ".zdList>.zditem{width: 100%;height: 104px;margin-bottom: 15px;}",
    ".zditem_active{border: 2px solid rgba(5,107,254,0.8)}",
    //zditem  top + footer
    ".zditem .top{height: 70px;cursor: pointer}",
    ".zditem.footer{height: 30px;}",
    ".top_run{background-color: #F5FAFF}", // 行驶
    ".top_stop{background-color: #FCE0D5}", // 静止
    ".top_lx{background-color: #EEEFF1}", // 离线
    ".footer_run{background-color: #CDE7FE}", // 行驶
    ".footer_stop{background-color: #FCB69D}", // 静止
    ".footer_lx{background-color: #D7D8DA}", // 离线
    ".zditem .footer>.footer_btns{display: inline-block; height: 30px;line-height: 30px; width: calc(33.3%);text-align: center;cursor: pointer}",
    // zditem  top
    ".top_checkbox{width: 30px;height: 70px;padding: 25px 10px 10px 15px;margin-right: 15px}",
    ".top_conent{width:auto;height: 70px }",

    ".topcontent_zdicon{width: 40px;height: 40px;margin: 15px 15px 15px 0px;background-repeat: no-repeat;background-size: 100% 100%}", /*终端图标*/
    ".topcontent_zdicon_run{background-image: url('assets/img/sjgz/zd_icon_run.png')}", // 行驶图标
    ".topcontent_zdicon_stop{background-image: url('assets/img/sjgz/zd_icon_stop.png')}", // 停止图标
    ".topcontent_zdicon_lx{background-image: url('assets/img/sjgz/zd_icon_lx.png')}", // 离线图标
    ".topcontent_txt1{width: 150px;height: 70px;padding: 5px 0px}", /*电量*/
    ".topcontent_txt2{width: 80px;height: 70px;padding: 5px 0px}", /*速度*/
    ".topcontent_txt1>.clmc{height: 70%}",
    ".topcontent_txt1>.dl{height: 30%;}",
    ".topcontent_txt1>.dl>.dl_txt{color: grey;padding-left: 10px}",
    ".topcontent_txt2>.speed{height: 70%;text-align: center}",
    ".topcontent_txt2>.zxtz{height: 30%;text-align: center}",
    ".text_run{color: #2196F3}",  // 【行驶】
    ".text_stop{color: red}",   //  【停止】
    ".text_zx{color: greenyellow}",
    ".text_lx{color: #969796}"
  ]
})
export class YwclCllbComponent implements OnInit, OnDestroy {
  compw: string = "0px";
  comph: string = "0px";
  topv: string = "0px";
  leftv: string = "0px";
  comptitle: string = "试卷押运车辆列表";
  frompage: string;
  title: string = "";  // 终端big title内容，登入用户的csmc
  // 检索条件
  s_obj: any = {
    sbmc: "",
    zxzt: "",
    ksgljgid: "",
    ksjhbh: ""
  };
  fzList: any[] = []; // 当前查询到的所有的终端
  zdlist_checked: any[] = [];  // 勾选的终端（地图上要显示实时位置点的）
  activezdobj: any; // 高亮的终端对象


  quickSeach(e: any): void {
    const keycode = e.keyCode;
    if (keycode == 13) {
      this.getdata();
    }
  }

  /**
   * 查询终端
   */
  getdata(): void {
    if (!this.s_obj.ksgljgid || !this.s_obj.ksjhbh) {
      return
    }
    // 每次搜索，终端列表变化， 地图上的终端信息还原
    this.sharedService.emitChange({
      actiontype: "activeZd",
      data: {
        zdlist: [],
        activezdobj: null
      }
    });
    // 在线搜索条件的处理
    let checkedv: string = ""; //全部
    $("input[name='sfzx']").each((index, item) => {
      if (item.checked) {
        checkedv = item.value;
      }
    });
    this.s_obj.zxzt = checkedv;
    const url = "sjgz/zsymyycl/sjyycllb";
    this.itservice.kwPtPost(url, this.s_obj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const sjyyclListv = resp.sjyyclList ? resp.sjyyclList : [];
            if (!sjyyclListv.length) {
              // 此次查询终端为空，清空统计数据
              this.fzList.length = 0;
              this.sharedService.emitChange({
                actiontype: "zdzttj",
                data: {
                  zdlist: []
                }
              });
              return
            }
            const allzdlist: any[] = [];
            this.fzList = sjyyclListv.map((item, index) => {
              const obj = {
                fzmc: item.fzmc,
                fzid: `fz_${index}`,
                fzexpand: false,
                checked: false,
                zdList: [],
              };
              const clListv = item.clList ? item.clList : [];
              const zdlistv = clListv.map((zdobj) => {
                allzdlist.push(zdobj);
                return {
                  checked: false,
                  active: false,
                  id: zdobj.sbid,
                  zdmc: zdobj.sbmc,
                  dl: zdobj.dl,
                  zxzt: zdobj.zxzt, // 0 在线；1 离线
                  zxztmc: (zdobj.zxzt == "1") ? "离线" : "在线",
                  sd: zdobj.sd,
                  gldzbqidList: item.gldzbqidList ? item.gldzbqidList : [], // 终端关联的电子标签id 列表
                }
              });
              obj.zdList = zdlistv;
              return obj;
            });
            // 搜索到的终端列表----统计  行驶/静止/离线的数量
            this.sharedService.emitChange({
              actiontype: "zdzttj",
              data: {
                zdlist: allzdlist
              }
            });
          }
        }
      });
    });
    // const testdata = [{
    //   fzmc: "武汉市教育考试中心",
    //   fzid: "fz01",
    //   fzexpand: true,
    //   checked: false,
    //   zdList: [{
    //     checked: false,
    //     active: false,
    //     id: "864131033229194",
    //     zdmc: "洪山区招办洪山区招办洪山区招办洪山区招办",
    //     dl: 0,
    //     zxzt: "0",  // 在线状态  0 = 在线  1 = 离线
    //     zxztmc: "在线",
    //     sd: 0,  // 实时更新的数据指标
    //     gldzbqidList: ["012", "0123"],
    //   }, {
    //     checked: false,
    //     active: false,
    //     id: "63433e096dafd5d3",
    //     zdmc: "武昌区招办",
    //     dl: 40,
    //     zxzt: "0",  // 在线状态  0 = 在线  1 = 离线
    //     zxztmc: "在线",
    //     sd: 25,  // 实时更新的数据指标
    //     gldzbqidList: ["012", "0123"],
    //   }, {
    //     checked: false,
    //     active: false,
    //     id: "ef9459b654674421",
    //     zdmc: "武昌区招办11111",
    //     dl: 40,
    //     zxzt: "1",  // 在线状态  0 = 在线  1 = 离线
    //     zxztmc: "离线",
    //     sd: 0,  // 实时更新的数据指标
    //     gldzbqidList: ["012", "0123"],
    //   }, {
    //     checked: false,
    //     active: false,
    //     id: "ef9459b61111111674421",
    //     zdmc: "武昌区招办222222222222",
    //     dl: 100,
    //     zxzt: "1",  // 在线状态  0 = 在线  1 = 离线
    //     zxztmc: "离线",
    //     sd: 10  // 实时更新的数据指标
    //   }]
    // }, {
    //   fzmc: "荆门市教育考试中心",
    //   fzid: "fz02",
    //   fzexpand: false,
    //   checked: false,
    //   zdList: []
    // }];
    // this.fzList = testdata;
  }


  /**
   * 分组展开/隐藏切换
   * @param fzobj
   */
  toggleFzexpand(fzobj: any): void {
    fzobj.fzexpand = !fzobj.fzexpand;
  }

  /**
   * 勾选控制
   * @param {number} type
   * 1--某个分组全选/取消全选
   * 2--某个终端选中/取消选中
   * 3---某个终端  高亮/取消高亮
   */
  checkedToggle(type: number, obj: any): void {
    switch (type) {
      case 1: {
        const fzid = obj.fzid;
        const fzchecked = obj.checked;
        const itfz_zdlist = obj.zdList;  // 分组下的终端列表
        // （1）分组下的  终端勾选状态   高亮状态处理
        itfz_zdlist.forEach((zdobj) => {
          if (fzchecked) {
            zdobj.checked = false;
            zdobj.active = false; //不勾选的终端 一定不高亮
            this.zdlist_checked = this.zdlist_checked.filter((zdobj2) => {
              return zdobj.id != zdobj2.id;
            });

            //取消高亮
            if (this.activezdobj) {
              if (this.activezdobj.id == zdobj.id) {
                // 高亮的终端在这个取消 分组下
                this.activezdobj = null;
              }
            }
          } else {
            zdobj.checked = true;
            this.zdlist_checked.push(zdobj);
          }
        });
        // (2)  分组自己的  勾选状态处理
        if (fzchecked) {
          obj.checked = false;
        } else {
          obj.checked = true;
        }
      }
        break;
      case 2: {
        //原则：  终端取消选中的，一定不能高亮
        // 取消选中的时候需要 ：  判断此是否是高亮，是高亮，取消高亮
        const zdid = obj.id;
        const zdchecked = obj.checked;
        const actived = obj.active;
        if (zdchecked) {
          obj.checked = false;
          this.zdlist_checked = this.zdlist_checked.filter((zdobj) => {
            return zdid != zdobj.id;
          });
          if (actived) {
            obj.active = false;
            this.activezdobj = null;
          }
        } else {
          obj.checked = true;
          this.zdlist_checked.push(Object.assign({}, obj));
        }
      }
        break;
      case 3: {
        // 原则： 终端高亮   一定要选中
        // （1）高亮还原 （2）设置此节点高亮：需要判断是否勾选，没勾选一定要设置勾选
        const zdid = obj.id;
        const zdchecked = obj.checked;
        const actived = obj.active;
        // 全部取消高亮
        this.fzList.forEach((item) => {
          const it_zdList = item.zdList;
          it_zdList.forEach((zdobj) => {
            zdobj.active = false;
          })
        });
        //设置这个终端是高亮
        obj.active = true;
        this.activezdobj = obj;
        if (!zdchecked) {
          obj.checked = true;
          this.zdlist_checked.push(Object.assign({}, obj));
        }
      }
        break;
    }

    this.zdlist_checked = this.commservice.fliterobjRepeat(this.zdlist_checked, "id");
    this.commservice.log("zdlist_checked", this.zdlist_checked);
    this.commservice.log("activezd", this.activezdobj);

    //广播，选中的终端列表，和当前高亮的终端对象
    this.sharedService.emitChange({
      actiontype: "activeZd",
      data: {
        zdlist: this.zdlist_checked,
        activezdobj: this.activezdobj
      }
    });
  }


  /**
   * 组件在 显示面板中的位置+ 大小
   */
  initcompPositionSize_ctrshow(): void {
    // 位置 大小
    this.compw = this.o.compw + "px";
    this.comph = this.o.comph + "px";
    this.topv = this.o.topv + "px";
    this.leftv = this.o.leftv + "px";
    // 显示
    this.frompage = this.o.frompage;
    if (this.frompage === "ywcl") {
      this.getdata();
    }
  }


  /**
   * 1---轨迹回放
   * 2--实时跟踪
   * @param {number} num
   */
  gotoPage(num: number): void {
    switch (num) {
      case 1:
        this.router.navigate(["sjgzxin.zs", "gjhf"]);
        break;
      case 2:
        break;
    }
  }

  @Input() o: any;
  @Output() outhander: EventEmitter<any> = new EventEmitter();

  constructor(private commservice: CommService,
              private itservice: MyhttpService,
              private router: Router,
              private localStorageService: LocalStorageService,
              private sharedService: SharedService) {
    this.sharedService.changeEmitted$.subscribe(resp => {
      const actiontype = resp.actiontype;
      const datav = resp.data;
      if (actiontype == "toggleActiveZd") {
        const activezdobj = datav.activezdobj;
        const activezdid = activezdobj ? activezdobj.id : "";
        this.fzList.forEach((item) => {
          const it_zdList = item.zdList;
          it_zdList.forEach((zdobj) => {
            if (activezdid == zdobj.id) {
              zdobj.active = true;
            } else {
              zdobj.active = false;
            }
          })
        });

      } else if (actiontype == "refresh_cllbzt") {
        this.fzList.forEach((item) => {
          const it_zdlist = item.zdList;
          it_zdlist.forEach((zdobj) => {
            const zdid = zdobj.id;
            if (datav.id_n == zdid) {
              zdobj.zxzt = datav.zxzt;
              zdobj.zxztmc = datav.zxztmc;
              zdobj.sd = datav.sd;
            }
          })
        });
      }
    });

  }

  ngOnInit() {
    this.commservice.log("-- 【 compkey=cllb】--被父组件动态加载init....", this.o);
    this.s_obj.ksjhbh = this.localStorageService.get("hksjh");
    this.commservice.getUserinfo((obj) => {
      this.title = obj.csmc;
      this.s_obj.ksgljgid = obj.csid;
      this.initcompPositionSize_ctrshow();
    });


    // $(document).click((e) => {
    //   const $target = $(e.target);
    //   if (!$target.is('.showctr') && !$target.is("i") && !$target.is(".myicon")) {
    //     $(".searchtree").removeClass("show");
    //   }
    // });
  }

  ngOnDestroy() {

  }

}
